//创建webSocket对象
var ws=new WebSocket("ws://39.107.110.18:3000/chat");  //访问资源和@ServerEndpoint相同
//给ws绑定事件
ws.onopen=function () {   //连接建立时触发

}
ws.onmessage=function (evt) {   //客户端接收服务端数据时触发,evt为服务端推送过来的消息
    //将获取到的josn字符串转换为对象
    var dataStr=evt.data;
    var msgResult = JSON.parse(dataStr);

    //判断是否为系统消息
    if(msgResult.type==0){
        //清空
        $('.menu2').html("");

        for(var index=0;index<con.$data.friends.length;index++){   //所有好友用户
        var flag=false;
        for(var username of msgResult.message){   //在线用户
            if(username==con.$data.friends[index].username){
                flag=true;
            }
        }
        con.$data.friends[index].state=flag;
        }
    }else if(msgResult.type==1){
        var str="<div>\n" +
            "       <div style='float: left;'>\n" +
            "           <img style='width: 30px;height: 30px;margin-top: 5px' src='https://img.gejiba.com/images/6fdc934e8cb5aa040764d0ff5b287d00.th.webp'>\n" +
            "       </div>\n" +
            "       <div style='float: left;'>\n" +
            "           <span class='left'>"+msgResult.formName+":</span><br>\n" +
            "           <div class='atalk'>\n" +
            "               <span class='lSpan'>"+msgResult.message+"</span>\n" +
            "           </div>\n" +
            "       </div>\n" +
            "    </div>"
        //如果是相对的窗口的消息,就渲染
        if(msgResult.formName==con.$data.toName){
            //渲染别人的消息
            $('.messageShow').append(str);
        }
        ///如果不是相对的窗口的消息，就存储起来
        //获取sessionstorage中的消息
        var charData=sessionStorage.getItem(msgResult.formName);
        if(charData!=null){
            str=charData+str;
        }
        //key为用户的姓名,value为html数据
        sessionStorage.setItem(msgResult.formName,str);
    }else{
        //获取请求列表
        con.list();
        //获取好友列表
        con.getFriends();

    }

}
ws.onclose=function () {    //连接关闭时触发

}

Vue.config.productionTip=false;  //以阻止 vue 在启动时生成生产提示。 <!-- 全局配置 -->

const con=new Vue({
    el: '#app',
    data:{
        //搜索弹层
        dialogSearchVisible: false,   //是否弹出的添加窗口
        //详情窗
        informationVisible: false,
        //请求列表
        dialogRequstVisible: false,
        activeIndex: '1',
        activeIndex2: '1',
        //用户信息
        userLoading: false,
        userData: {

        },
        //正在和谁聊天
        toName: '',
        //输入信息
        formData: '',
        //好友列表
        friends: [],
        //行点击id
        rowid: 0,
        //搜索数据
        searchData: '',
        //搜索出的好友
        searchFriends: [],
        //详情
        information: {

        },
        //请求添加列表
        demands:[]

    },
    //钩子函数，VUE对象初始化完成后自动执行
    created(){
        this.getUser();
        this.getFriends();
        this.list();
    },
    methods:{
        //获取用户信息
        getUser(){
            axios({
                method: "get",
                url: "/user/getUser",
            }).then((res)=>{
                if(res.data.flag){
                    this.userLoading=true;
                    this.userData=res.data.data;
                }else{
                    this.userLoading=false;
                }
            });
        },
        handleSelect1(key, keyPath) {

        },
        //获取好友列表
        getFriends(){
            axios({
                method: "get",
                url: "/friend/getFriends",
            }).then((res)=>{
                if(res.data.flag){
                    this.friends=res.data.data;
                }else{

                }
            });
        },
        //侧面菜单,点击反应
        handleSelect2(row,event,column) {   //key为index属性值
            for(var friend of this.friends){
                if(row.id==friend.id){
                    this.toName=friend.username;
                }
            }
            //详情赋值
            this.information.username=this.toName;
            this.information.gender=row.gender;
            this.information.phone=row.phone;
            this.information.email=row.email;

            //清空聊天区
            $('.messageShow').html('');
            //显示消息展示区输入区等
            $('.empty').css('display','none');
            $('.context').css('display','inline');
            //获取sessionStorage中的信息
            var chatData=sessionStorage.getItem(this.toName);
            if(chatData!=null){
                //渲染出信息
                $(".messageShow").html(chatData);
            }
        },
        //发送消息
        submit(){
            var json={"toName": this.toName,"message":this.formData,is_add:false};
            //渲染自己的消息
            var str="<div>\n" +
                "       <div style='float: right;'>\n" +
                "           <img style='width: 30px;height: 30px;margin-top: 5px' src='https://img.gejiba.com/images/6fdc934e8cb5aa040764d0ff5b287d00.th.webp'>\n" +
                "       </div>\n" +
                "       <div style='float: right;'>\n" +
                "           <span class='right'>我:</span><br>\n" +
                "           <div class='btalk'>\n" +
                "               <span class='rSpan'>"+this.formData+"</span>\n" +
                "           </div>\n" +
                "       </div>\n" +
                "    </div>"
            $('.messageShow').append(str);
            //获取sessionStorage中的信息
            var chatData=sessionStorage.getItem(this.toName);
            if(chatData!=null){
                str=chatData+str;
            }

            //发送数据给服务端，由@OnMessage接收
            ws.send(JSON.stringify(json));   //stringify转为字符串
            this.formData='';
        },
        //用户名操作
        usernamef(row,index){
            return row.username.length>7?row.username.substring(0,5)+'...':row.username;
        },
        //状态操作
        statef(row,index){
            return row.state==true?'在线':'离线';
        },
        //行变色事件
        rowStyle(row, rowIndex){

        },
        //打开添加层
        openSearch(){
            this.dialogSearchVisible=true;
        },
        //搜索联系人
        searchUser(){
            axios({
                method: "get",
                url: "/user/searchUser",
                params:{
                    searchData: this.searchData
                }
            }).then((res)=>{
                if(res.data.flag){
                    this.searchFriends=res.data.data;
                }else{

                }
            });
        },
        //查看好友信息
        selectId(){
            this.informationVisible=true;
        },
        //查询陌生人详情
        select(row){
            this.informationVisible=true;
            this.information.username=row.username;
            this.information.gender=row.gender;
            this.information.phone=row.phone;
            this.information.email=row.email;
        },
        //性别转换
        gender(sex){
            if(sex==0){
                return '女';
            }else{
                return '男';
            }
        },
        //添加好友
        sendRequest(row){
            this.$confirm("您确认发送添加请求，是否继续？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {   //选择确定的情况
                axios({
                    method: "POST",
                    url: "/demand/add",
                    data: {
                        fid: this.userData.uid,
                        tid: row.uid,
                        fromName: this.userData.username,
                        toName: row.username,
                        avatar: row.avatar,
                    }
                }).then((res) => {
                    if (res.data.flag) {
                        this.$message({
                            message: res.data.message,
                            type: "success"
                        });
                        var json={"toName": row.username,"message":"","is_add":true};
                        //发送数据给服务端，由@OnMessage接收
                        ws.send(JSON.stringify(json));   //stringify转为字符串
                    } else {
                        this.$message(res.data.message);
                    }
                });
                this.dialogSearchVisible = false;
            }).catch(() => {     //选择取消的情况
                this.$message({
                    type: "into",
                    message: "已取消"
                });
            });
        },
        //请求列表展示
        list(){
            axios({
                method: "get",
                url: "/demand/list",
            }).then((res) => {
                if (res.data.flag) {
                    this.demands=res.data.data;
                }
            });
        },
        //同意请求
        toAdd(row){
            axios({
                method: "PUT",
                url: "/demand/toAdd",
                params: {
                    id: row.id,
                    fromId: row.fid,
                    toId: row.tid
                }
            }).then((res) => {
                if (res.data.flag) {
                    this.$message({
                        message: res.data.message,
                        type: "success"
                    });
                    var json={"toName": row.fromName,"message":"","is_add":true};
                    //发送数据给服务端，由@OnMessage接收
                    ws.send(JSON.stringify(json));   //stringify转为字符串
                } else {
                }
            });
            this.dialogRequstVisible=false;
        },
        //不同意请求
        toRemove(row){

        },
        //搜素页查看详情
        requestSelect(row){
            axios({
                method: "get",
                url: "/user/getUserID",
                params: {
                    uid: row.fid
                }
            }).then((res) => {
                if (res.data.flag) {
                    this.information=res.data.data;
                }
            });
            this.informationVisible=true;
        }
    }
});